from django.db import models
from django.contrib.auth.models import User
from ckeditor_uploader.fields import RichTextUploadingField
from django.contrib.contenttypes.fields import GenericRelation
from read_statistics.models import ReadNumExpandMethod,ReadDetall
from django.urls import reverse

# from ckeditor.fields import RichTextField #pip 安装ckeditor 库（富文本编辑器）
# Create your models here.




class BlogType(models.Model):
    type_name = models.CharField(max_length=30,verbose_name="类型")

    def __str__(self):
        return self.type_name


    class Meta:
        verbose_name = '博客类型'
        verbose_name_plural = '博客类型'


# ##博客
class Blog(models.Model,ReadNumExpandMethod):
    title = models.CharField(max_length=50,verbose_name="标题")
    content = RichTextUploadingField(verbose_name="内容")
    created_time = models.DateTimeField(auto_now_add=True,verbose_name="创建时间")
    last_update_time = models.DateTimeField(auto_now=True,verbose_name="修改时间")
    read_details = GenericRelation(ReadDetall)
    blog_type = models.ForeignKey(BlogType,on_delete=models.CASCADE,verbose_name="类型") #类型
    author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="作者")  ##作者


        # try:
        #     return self.readnum.read_num
        # except exceptions.ObjectDoesNotExist:
        #     return 0
    def get_url(self):
        return reverse('blog_datell',kwargs={'blog_pk' : self.pk})

    def get_user(self):
        return self.author

    def get_email(self):
        return self.author.email

    def __str__(self):

        return "<Blog:%s>" % self.title

    # 排序
    class Meta:
        ordering = ['-created_time']
        verbose_name = '博客'
        verbose_name_plural = '博客'



'''
class ReadNum(models.Model):
    read_num = models.IntegerField(default=0)  ##计数
    blog = models.OneToOneField(Blog,on_delete=models.DO_NOTHING)
'''